package com.imonsoft.sqm.validator.basedata;

import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.service.MessageUtil;
import com.imonsoft.sqm.service.basedata.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.*;

import java.util.ArrayList;
import java.util.List;

@Component("supplierValidator")
public class SupplierValidator implements Validator {

	@Autowired
	private SupplierService supplierService;

	@Override
	public boolean supports(Class<?> clazz) {
		return Supplier.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "message.required.supplier.code", "code required!");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "message.required.supplier.name", "name required!");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mail", "message.required.supplier.mail", "mail required!");
		//ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "message.required.supplier.phone", "phone required!");
		//ValidationUtils.rejectIfEmptyOrWhitespace(errors, "linkman", "message.required.supplier.linkman", "linkman required!");
        //ValidationUtils.rejectIfEmptyOrWhitespace(errors, "materialGroup", "message.required.supplier.materialGroup", "materialGroup required!");

    }
    public void methodAddValidate(Object target, Errors errors){
        validate(target,errors);
        Supplier supplier = (Supplier) target;
        List<Supplier> supplierList = supplierService.findSupplierByCode(supplier.getCode());
        if (supplierList.size() > 0) {
            errors.rejectValue("code", "message.unique.supplier.code", new Object[] { supplier.getCode() }, "编码不能重复！");
        }
    }
    public void methodModifyValidate(Object target, Errors errors){
        validate(target,errors);
        Supplier supplier = (Supplier) target;
        List<Supplier> supplierList = supplierService.findSupplierByCode(supplier.getCode());
        if (supplierList.size() == 1
                && supplierList.get(0).getId().intValue()!=supplier.getId().intValue()) {
            errors.rejectValue("code", "message.unique.supplier.code", new Object[] { supplier.getCode() }, "编码不能重复！");
        }
    }

    @Autowired
    private MessageUtil messageUtil;
    public List<String> getErrors(BindingResult result){
        List<String> errors = new ArrayList<String>();
        for (ObjectError error : result.getAllErrors()) {
            errors.add(messageUtil.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage()));
        }
        return errors;
    }
}
